package tpch

import (
	"database/sql"
	"fmt"
	"log"
	"sort"
	"strconv"
	"time"

	_ "github.com/lib/pq"
)

const (
	base_format = "2006-01-02"
	database    = "tpchp"
	//table = "orders"
	table      = "lineitem"
	dataSource = "user=root dbname=tpchp host=node2.cloud.com port=9001 sslmode=disable"
	internal   = "zbdb_internal"

	orders_partition_prefix   = "orders_part_"
	lineitem_partition_prefix = "li_part_"
	o_part_len                = len(orders_partition_prefix)
	li_part_len               = len(lineitem_partition_prefix)
)

type PartitionRange struct {
	from time.Time
	to   time.Time
}

var (
	partitions = make(map[int]PartitionRange)
	partIds []int
)

func init() {
	db, err := sql.Open("postgres", dataSource)
	if err != nil {
		log.Fatal("error connecting to the database: ", err)
	}
	defer db.Close()

	query := fmt.Sprintf("select p.table_id, p.name, p.columns, p.column_names, p.type, p.values \n"+
		"from %s.partitions p join %s.tables t on p.table_id=t.table_id \n"+
		"where t.name='%s' and t.database_name='%s' and t.state='PUBLIC' and t.drop_time is null\n"+
		"order by p.values asc",
		internal, internal, table, database)
	fmt.Println(query)
	rows, err := db.Query(query)
	if err != nil {
		log.Fatal("error connecting to the database: ", err)
	}

	defer rows.Close()

	for rows.Next() {
		var (
			tableId     int
			name        string
			columns     string
			columnNames string
			_type       string
			values      string
		)
		if err := rows.Scan(&tableId, &name, &columns, &columnNames, &_type, &values); err != nil {
			log.Printf("%s\n", err)
		}

		//fmt.Printf("%d %s %s %s %s %s \n", tableId, name, columns, columnNames, _type, values, )
		//partitionId, err := strconv.Atoi(name[o_part_len:])
		partitionId, err := strconv.Atoi(name[li_part_len:])
		if err != nil {
			log.Printf("%s\n", err)
		}

		if "range" == _type {
			//fmt.Printf("\t[%s, %s)", values[7:7+10], values[25:25+10])
			from, pe1 := time.Parse(base_format, values[7:7+10])
			to, pe2 := time.Parse(base_format, values[25:25+10])
			if pe1 != nil || pe2 != nil {
				log.Printf("%s\n", pe1)
			}
			partiton := PartitionRange{
				from: from,
				to:   to,
			}

			partitions[partitionId] = partiton
		}
	}
	partIds = make([]int, 0, len(partitions))
	for id, _ := range partitions {
		partIds = append(partIds, id)
	}

	sort.Ints(partIds)
}
